var designClass = "design_class", hideClass = "hide_class", browseClass = "browse_class", addClass = "add_class", editClass = "edit_class";
var upWindow = window.parent.frames["zwIframe"];
if (!upWindow) {
    try {
        upWindow = window.parent.frames["componentDiv"].frames["zwIframe"];
    } catch (e) {
        upWindow = null;
    }
}
if (!upWindow) {
    upWindow = window.parent.frames["main"].document.getElementById("summary").contentWindow.frames["componentDiv"].frames["zwIframe"];
}
function fy_dialog_close() {
	// window.parent.$(".mask").remove();
	// window.parent.parent.$(".layui-layer-iframe").parent().find(".layui-layer-close").trigger("click");
	window.parent.$(".layui-layer-iframe").parent().find(".layui-layer-close").trigger(
			"click");
}

function getUpFields(name) {
	return upWindow.$("[validate*='name:\"" + name + "\"']");
}
function getUpFieldsByFieldval(name) {
	return upWindow.$("[fieldval*='displayName:\"" + name + "\"']");
}
function getUpAccountFieldValue(name) {
	var field = getUpFields(name).eq(0);
	return {
		displayValue : field.is("span") ? field.text() : field.val(),
		value : eval("(" + field.parent("span").attr("fieldVal") + ")").value
	};
}

function getUpFieldValue(field) {
	var fieldVal = field.attr("fieldVal");
	var editTag = field.hasClass(editClass);
	var browseTag = field.hasClass(browseClass);
	var addTag = field.hasClass(addClass);
	if (fieldVal != null && typeof (fieldVal) != 'undefined') {
		fieldVal = eval("(" + fieldVal + ")");
	} else {
		return null;
	}
	var obj = new Object();
	obj.displayName = fieldVal.displayName;
	obj.name = fieldVal.name;
	var tag = true;
	switch (fieldVal.inputType) {
	case "text":
	case "textarea":

		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = fieldVal.value;
		} else if (addTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		}
		break;
	case "checkbox":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		}
		break;
	case "radio":
		if (editTag) {
			obj.value = field.find(":radio:checked").attr("val4cal");
		} else if (browseTag) {
			obj.value = field.find(":radio:checked").attr("val4cal");
		}
		break;
	case "select":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name + " option:selected")
					.attr("val4cal");
		} else if (browseTag) {
			obj.value = field.find("#" + fieldVal.name).attr("val4cal");
		}
		break;
	case "date":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
			if (obj.value != "") {
				obj.value = obj.value + " 00:00";
			}
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "datetime":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "flowdealoption":
		if (editTag) {
			obj.value = fieldVal.value;
		} else if (browseTag) {
			obj.value = fieldVal.value;
		} else if (addTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "lable":
		if (editTag) {
			obj.value = fieldVal.value;
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "relationform":
		if (editTag) {
			obj.value = fieldVal.value;
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "relation":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "project":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "member":
	case "multimember":
	case "account":
	case "multiaccount":
	case "department":
	case "multidepartment":
	case "post":
	case "multipost":
	case "level":
	case "multilevel":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name + "_txt").val();
		} else if (browseTag) {
			obj.value = field.find("#" + fieldVal.name).text();
		}
		break;
	case "attachment":
	case "image":
	case "document":
		if (editTag || browseTag) {
			var attNames = "";
			var tempField = field.find("#" + fieldVal.name);
			var tempFileId = "";
			if (tempField[0].tagName.toLowerCase() == "input") {
				tempFileId = tempField.val();
			} else if (tempField[0].tagName.toLowerCase() == "span") {
				tempFileId = tempField[0].innerHTML;
			}
			var atts = upWindow.getAttBySubreference(tempFileId);
			for ( var j = 0; j < atts.length; j++) {
				attNames += atts[j].filename + ",";
			}
			if (attNames != "") {
				attNames = attNames.substr(0, attNames.length - 1);
			}
			obj.value = attNames;
		}
		break;
	case "outwrite":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "externalwrite-ahead":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "exchangetask":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "querytask":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	default:
		tag = false;
	}
	if (obj.value != undefined) {
		obj.value = obj.value.replace("\r\n", ";");
		obj.value = obj.value.replace("\n", ";");
	}
	return obj;
}
function setUpFieldValue(name, value) {
	upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input").val(
			value);
	upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input")
			.trigger("blur");
}

function setUpFieldValue2(field, value, displayValue, index) {

	try {

		var fieldVal = field.attr("fieldVal");
		var editTag = field.hasClass(editClass);
		var addTag = field.hasClass(addClass);
		value = trim(value);
		displayValue = trim(displayValue);
		if (fieldVal != null && typeof (fieldVal) != 'undefined') {
			fieldVal = eval("(" + fieldVal + ")");
		} else {
			return null;
		}
		var tag = true;
		switch (fieldVal.inputType) {
		case "text":
		case "textarea":
			if (editTag) {
				var inField = field.find("#" + fieldVal.name);
				inField.val(value);
				inField.trigger("blur");
			} else if (addTag) {
				var inField = field.find("#" + fieldVal.name);
				inField.val(value);
				inField.trigger("blur");
			}
			break;
		case "checkbox":
			if (editTag) {
				field.find("#" + fieldVal.name).attr("checked", true);
				field.find("#" + fieldVal.name).trigger("click");
			}
			break;
		case "radio":
			if (editTag) {
				field.find(":radio").eq(index).attr("checked", true);
				field.find(":radio").eq(index).trigger("click");
			}
			break;
		case "select":
			if (editTag) {
				// if (value) {
				// field.find("#" + fieldVal.name).value(value);
				// } else {
				var options = field.find("#" + fieldVal.name + " option");
				for ( var k = 0; k < options.length; k++) {
					if (options.eq(k).text() == value)
						options.eq(k).attr("selected", true);
				}
				// }
				field.find("#" + fieldVal.name).trigger("change");
			}
			break;
		case "date":
			if (editTag) {
				field.find("#" + fieldVal.name).val(value);
				field.find("#" + fieldVal.name).trigger("blur");
			}
			break;
		case "datetime":
			if (editTag) {
				field.find("#" + fieldVal.name).val(value);
				field.find("#" + fieldVal.name).trigger("blur");
			}
			break;
		case "member":
		case "multimember":
		case "account":
		case "multiaccount":
		case "department":
		case "multidepartment":
		case "post":
		case "multipost":
		case "level":
		case "multilevel":
			if (editTag) {
				alert(editTag);
				field.find("#" + fieldVal.name + "_txt").val(value);
			}
			break;
		}
	} catch (e) {
		// TODO: handle exception
	}
}

/**
 * 去除左右空格
 */
function trim(str) {
	return (str) ? (typeof str == "string" ? str.replace(/^\s*/, "").replace(
			/\s*$/, "") : str) : "";
}

function $(name) {
	return document.getElementsByName(name);
}

function getArrayParams(array, link) {
	for ( var i = 0; i < array.length; i++) {
		var temp = array[i];
		array[i] = encodeURIComponent(temp);
	}
	return array.join(link);
}

function replaceIllegalCharacter(field) {
	var charlist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	charlist += "abcdefghijklmnopqrstuvwxyz";
	charlist += "0123456789";
	charlist += " `~!@#$%^&*()_+-={}|[]\:\\\";'<>?,./";// 半角空格

	var providerName = field.value;
	var result = "";
	for ( var i = 0; i < providerName.length; i++) {
		var c1 = providerName.charAt(i);
		var c2 = providerName.charCodeAt(i);
		if ("　" == c1) {
			result += " ";
		} else if ("，" == c1) {
			result += ",";
		} else if ("。" == c1) {
			result += ".";
		} else {
			if (charlist.indexOf(String.fromCharCode(c2 - 65248)) > -1) {
				result += String.fromCharCode(c2 - 65248);
			} else {
				result += c1;
			}
		}
	}
	field.value = result.toUpperCase().replace(/^\s*/, "").replace(/\s*$/, "");
}

function writeCodeToForm() {
	var supplierCodes = getUpFieldsByFieldval("供应商编码1");
	var supplierCodeNodes = $("supplierCode");
	for ( var i = 0; i < supplierCodes.length; i++) {
		setUpFieldValue2(supplierCodes.eq(i), supplierCodeNodes[i].value);
	}
	fy_dialog_close();
}

// function onSupplierNameChange(field) {
// replaceIllegalCharacter(field);
// }
function corpValueChange(node) {
	var selectNodes = $('corpSelect');
	for ( var i = 0; i < selectNodes.length; i++) {
		selectNodes[i].value = node.value;
	}
}
function createOption(msg,key){
	var op = document.createElement("option");
	op.value = key;
	op.text = msg;
	return op;
}
function init() {
	alert("test11111");
	if (getUpFieldsByFieldval('填单状态').length > 0
			&& getUpFieldValue(getUpFieldsByFieldval('填单状态')).value == "code") {
		alert("填单状态")
		var firstTR = getParentTR($('corpSelect')[0]);
		var repeatOperator = new RepeateTableOperator(firstTR.parentNode);
		repeatOperator.addListeners(firstTR);
		repeatOperator.setAllowAdd(false);
		repeatOperator.setAllowDel(false);
		$('corpSelect')[0].options.add(createOption(
				getUpFieldValue(getUpFieldsByFieldval("供应制造部").eq(0)).value,
				getUpFieldValue(getUpFieldsByFieldval("制造部ID").eq(0)).value));
		$('corpSelect')[0].options.selectedIndex = 0;

		var supplierNames = getUpFieldsByFieldval("供应商名称");
		repeatOperator.addEmptyTR(firstTR, supplierNames.length - 1);
		var checkArray = [];

		for ( var i = 0; i < supplierNames.length; i++) {
			checkArray.push(getUpFieldValue(supplierNames.eq(i)).value);
			$("supplierName")[i].value = getUpFieldValue(supplierNames.eq(i)).value;
			$("supplierName")[i].readOnly = true;
			$("supplierName")[i].className = 'readonly';
			$("remark")[i].value = getUpFieldValue(getUpFieldsByFieldval("备注")
					.eq(i)).value;
			$("remark")[i].readOnly = true;
			$("remark")[i].className = 'readonly';
			$("supplierCode")[i].value = getUpFieldValue(getUpFieldsByFieldval(
					"供应商编码").eq(i)).value;
			$("supplierCode")[i].readOnly = false;
			$("supplierCode")[i].className = 'fill';
			$('corpSelect')[i].disabled = true;
		}

		if (checkArray.length > 0) {
			_ajax(
					'../oa2uapController.do?method=supplierExist&operate=3&checkArray='
							+ getArrayParams(checkArray, ('&checkArray=')),
					function(result) {
						var obj = eval('(' + result + ')');
						if (obj.success) {
							var info = obj.msg;
							var supplierNameNodes = $("supplierName");
							for ( var i = 0; i < supplierNameNodes.length; i++) {
								for ( var j = 0; j < info.length; j++) {
									if (supplierNameNodes[i].value
											&& info[j].name
											&& supplierNameNodes[i].value == info[j].name) {
										$("supplierCode")[i].value = info[j].code;
										$("supplierCode")[i].readOnly = true;
										$("supplierCode")[i].className = 'readonly';
										break;
									}
								}
							}
						} else {
							alert(obj.msg);
						}
					}, true);
		}

	} else {
		var firstTR = getParentTR($('corpSelect')[0]);
		var repeatOperator = new RepeateTableOperator(firstTR.parentNode);
		repeatOperator.addListeners(firstTR);
		repeatOperator.setAfterAddTrOperate(function() {
			for ( var i = 1; i < $('corpSelect').length; i++) {
				$('corpSelect')[i].value = $('corpSelect')[0].value;
			}
		});
		var oaAccountID = getUpAccountFieldValue('单位选择器').value;


		for ( var key in corpMap) {
			console.log(corpMap[key]+"--->"+corpMap[key][1])
			console.log(corpMap[key] == oaAccountID)
			if (corpMap[key] && corpMap[key] == oaAccountID) {
				alert("here")
				try {
					$('corpSelect')[0].options.add(createOption(corpMap1[key][1],
							key));

					if (oaAccountID == "5686590792835548528") {
						$('corpSelect')[0].options.add(createOption(
								"福州福耀模具科技有限公司", "key_1027"));
					}

					if (oaAccountID == "5348717256083522828") {
						$('corpSelect')[0].options.add(createOption("保定福耀玻璃有限公司",
								"key_1036"));
					}
				} catch (e1) {
					var op = document.createElement("option")
					op.text = corpMap1[key][1];
					op.value = key;
					$('corpSelect')[0].options.add(op);

					if (oaAccountID == "5686590792835548528") {
						
						var op1 = document.createElement("option")
						op1.text = "福州福耀模具科技有限公司";
						op1.value = "key_1027";
						
						$('corpSelect')[0].options.add(op1);
					}

					if (oaAccountID == "5348717256083522828") {
						var op2 = document.createElement("option")
						op2.text = "保定福耀玻璃有限公司";
						op2.value = "key_1036";
						$('corpSelect')[0].options.add(op2);
					}

				}
				break;
			}
		}
		$('corpSelect')[0].options.selectedIndex = 0;
		var upAccountID = getUpFieldValue(getUpFieldsByFieldval("制造部ID").eq(0)).value;
		if (oaAccountID == "5686590792835548528") {
			if (upAccountID != "") {
				$('corpSelect')[0].value = upAccountID;
			}
		}

		var supplierNames = getUpFieldsByFieldval("供应商名称");
		repeatOperator.addEmptyTR(firstTR, supplierNames.length - 1);
		for ( var i = 0; i < supplierNames.length; i++) {
			if (upAccountID != "")
				$('corpSelect')[i].value = upAccountID;
			$("supplierName")[i].value = getUpFieldValue(supplierNames.eq(i)).value;
			$("remark")[i].value = getUpFieldValue(getUpFieldsByFieldval("备注")
					.eq(i)).value;
		}
	}
}

function _ajax(url, operator, check) {
	document.getElementById("lodingDiv").style.display = '';
	var xmlhttp = null;
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
		xmlhttp = new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				text = xmlhttp.responseText;
				if (text == 1) {
					operator();
				} else if (text == 2) {
					alert("用户还未登陆，或者已掉线");
				} else if (text == 3) {
					alert("供应商名称/制造部ID不能为空。");
				} else {
					if (check)
						operator(text);
					else
						alert(text);
				}
			} else {
				alert("连接服务器异常");
			}
			document.getElementById("lodingDiv").style.display = 'none';
		}
	};
	xmlhttp.open("post", url + "&temp=" + Math.random(), true);
	xmlhttp.send();
}

window.onload = function() {
	document.getElementById("ok_button").onclick = function() {
		var corpID = $('corpSelect')[0].value;
		if (!corpID || corpID == "") {
			alert("获取制造部ＩＤ失败");
			return;
		}

		var checkArray = [];
		if (getUpFieldsByFieldval('填单状态').length > 0
				&& getUpFieldValue(getUpFieldsByFieldval('填单状态')).value == "code") {
			var supplierCodeNodes = $("supplierCode");
			var tempArray = [];
			for ( var i = 0; i < supplierCodeNodes.length; i++) {
				if (supplierCodeNodes[i].value == "") {
					alert("供应商编码不能为空");
					return;
				} else {

					for ( var j in tempArray) {
						if (tempArray[j] == supplierCodeNodes[i].value) {
							alert("供应商编码不能重复，重复的供应商编码为："
									+ supplierCodeNodes[i].value);
							return;
						}
					}
					tempArray.push(supplierCodeNodes[i].value);
					if (supplierCodeNodes[i].className == 'fill')
						checkArray.push(supplierCodeNodes[i].value);
				}
			}
			tempArray = null;
			if (checkArray.length > 0) {
				_ajax(
						'../oa2uapController.do?method=supplierExist&operate=2&checkArray='
								+ getArrayParams(checkArray, ('&checkArray='))
								+ "&corpID=" + corpID, function(data) {
							var result = eval("(" + data + ")");
							if (result.success) {
								if (result.msg) {
									alert(result.msg);
								}
								writeCodeToForm();
							} else {
								alert(result.msg);
							}
						}, true);
			} else {
				writeCodeToForm();
			}
		} else {
			var supplierNameNodes = $("supplierName");
			for ( var i = 0; i < supplierNameNodes.length; i++) {
				if (supplierNameNodes[i].value == "") {
					alert("供应商名称不能为空");
					return;
				} else {
					for ( var j in checkArray) {
						if (checkArray[j] == supplierNameNodes[i].value) {
							alert("供应商名称不能重复，重复的供应商名称为："
									+ supplierNameNodes[i].value);
							return;
						}
					}
					checkArray.push(supplierNameNodes[i].value);
				}
			}

			function write() {
				var supplierNames = getUpFieldsByFieldval("供应商名称");

				var oldLength = supplierNames.length;
				var newLength = supplierNameNodes.length;
				var tbody = supplierNames.eq(0).parent();
				while (!tbody.is("tbody")) {
					tbody = tbody.parent();
				}
				for ( var i = 0, length = Math.abs(newLength - oldLength); i < length; i++) {
					if (newLength > oldLength) {
						upWindow.fy_addEmpty(tbody.children().last());
					} else {
						upWindow.fy_delCurrentRepeat(tbody.children().last());
					}
				}

				for ( var i = 0; i < supplierNameNodes.length; i++) {
					if (supplierNameNodes[i].value == "") {
						alert("供应商名称不能为空");
						return;
					}
					setUpFieldValue2(getUpFieldsByFieldval("供应商名称1").eq(i),
							supplierNameNodes[i].value);
					setUpFieldValue2(getUpFieldsByFieldval("备注").eq(i),
							$("remark")[i].value);
					setUpFieldValue2(getUpFieldsByFieldval("供货类别1").eq(i), '无');
					setUpFieldValue2(
							getUpFieldsByFieldval("供应制造部1").eq(i),
							$("corpSelect")[i].options[$("corpSelect")[i].options.selectedIndex].text);
					setUpFieldValue2(getUpFieldsByFieldval("制造部ID").eq(i),
							$("corpSelect")[i].value);
				}
				fy_dialog_close();
			}
			_ajax(
					'../oa2uapController.do?method=supplierExist&operate=1&checkArray='
							+ getArrayParams(checkArray, ('&checkArray='))
							+ "&corpID=" + corpID, write);
		}

	};

	init();
};
